<template>
  <div class="job-form">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">{{ isEdit ? '编辑岗位' : '发布岗位' }}</span>
          <el-button @click="handleBack">返回</el-button>
        </div>
      </template>

      <div class="form-content">
        <el-form
          :model="jobForm"
          :rules="jobRules"
          ref="jobFormRef"
          label-width="120px"
          size="default"
        >
          <!-- 基本信息 -->
          <el-divider content-position="left">基本信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="所属公司" prop="company">
                <el-select
                  v-model="jobForm.company"
                  placeholder="请选择公司"
                  filterable
                  style="width: 100%"
                  @focus="loadCompanies"
                >
                  <el-option
                    v-for="company in companyList"
                    :key="company.id"
                    :label="company.name"
                    :value="company.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职位名称" prop="title">
                <el-input v-model="jobForm.title" placeholder="请输入职位名称" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作性质" prop="job_type">
                <el-select v-model="jobForm.job_type" placeholder="请选择工作性质" style="width: 100%">
                  <el-option label="全职" value="full_time" />
                  <el-option label="兼职" value="part_time" />
                  <el-option label="实习" value="internship" />
                  <el-option label="合同工" value="contract" />
                  <el-option label="远程工作" value="remote" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作方式" prop="work_mode">
                <el-select v-model="jobForm.work_mode" placeholder="请选择工作方式" style="width: 100%">
                  <el-option label="线上" value="online" />
                  <el-option label="线下" value="offline" />
                  <el-option label="混合" value="hybrid" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="工作地区" prop="work_location">
                <el-input v-model="jobForm.work_location" placeholder="请输入工作地区" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属部门">
                <el-input v-model="jobForm.department" placeholder="请输入所属部门" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 薪资信息 -->
          <el-divider content-position="left">薪资信息</el-divider>

          <el-form-item label="薪资设置">
            <el-radio-group v-model="salaryType">
              <el-radio label="range">薪资范围</el-radio>
              <el-radio label="negotiable">面议</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row :gutter="20" v-if="salaryType === 'range'">
            <el-col :span="12">
              <el-form-item label="最低薪资" prop="salary_min">
                <el-input-number
                  v-model="jobForm.salary_min"
                  :min="0"
                  :step="1000"
                  placeholder="请输入最低薪资"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高薪资" prop="salary_max">
                <el-input-number
                  v-model="jobForm.salary_max"
                  :min="0"
                  :step="1000"
                  placeholder="请输入最高薪资"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 职位要求 -->
          <el-divider content-position="left">职位要求</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="学历要求">
                <el-select v-model="jobForm.education_requirement" placeholder="请选择学历要求" style="width: 100%">
                  <el-option label="不限" value="不限" />
                  <el-option label="高中及以上" value="高中及以上" />
                  <el-option label="大专及以上" value="大专及以上" />
                  <el-option label="本科及以上" value="本科及以上" />
                  <el-option label="硕士及以上" value="硕士及以上" />
                  <el-option label="博士及以上" value="博士及以上" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经验要求">
                <el-input v-model="jobForm.experience_requirement" placeholder="请输入经验要求" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="职位描述" prop="description">
            <el-input
              v-model="jobForm.description"
              type="textarea"
              :rows="4"
              placeholder="请输入职位描述"
            />
          </el-form-item>

          <el-form-item label="岗位职责" prop="responsibilities">
            <el-input
              v-model="jobForm.responsibilities"
              type="textarea"
              :rows="4"
              placeholder="请输入岗位职责"
            />
          </el-form-item>

          <el-form-item label="任职要求" prop="requirements">
            <el-input
              v-model="jobForm.requirements"
              type="textarea"
              :rows="4"
              placeholder="请输入任职要求"
            />
          </el-form-item>

          <el-form-item label="福利待遇">
            <el-input
              v-model="jobForm.benefits"
              type="textarea"
              :rows="3"
              placeholder="请输入福利待遇"
            />
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="必备技能">
                <el-input v-model="jobForm.required_skills" placeholder="请输入必备技能，用逗号分隔" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先技能">
                <el-input v-model="jobForm.preferred_skills" placeholder="请输入优先技能，用逗号分隔" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 招聘信息 -->
          <el-divider content-position="left">招聘信息</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="招聘人数" prop="positions_available">
                <el-input-number
                  v-model="jobForm.positions_available"
                  :min="1"
                  placeholder="请输入招聘人数"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请截止时间">
                <el-date-picker
                  v-model="jobForm.application_deadline"
                  type="datetime"
                  placeholder="请选择申请截止时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 联系方式 -->
          <el-divider content-position="left">联系方式</el-divider>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="投递邮箱" prop="contact_email">
                <el-input v-model="jobForm.contact_email" placeholder="请输入简历投递邮箱" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话">
                <el-input v-model="jobForm.contact_phone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 有效时间 -->
          <el-divider content-position="left">有效时间</el-divider>

          <el-form-item label="有效期设置">
            <el-radio-group v-model="validityType">
              <el-radio label="long_term">长期有效</el-radio>
              <el-radio label="date_range">指定时间段</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-row :gutter="20" v-if="validityType === 'date_range'">
            <el-col :span="12">
              <el-form-item label="有效期开始" prop="valid_from">
                <el-date-picker
                  v-model="jobForm.valid_from"
                  type="datetime"
                  placeholder="请选择有效期开始时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效期结束" prop="valid_until">
                <el-date-picker
                  v-model="jobForm.valid_until"
                  type="datetime"
                  placeholder="请选择有效期结束时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-checkbox v-model="jobForm.is_featured">设为推荐岗位</el-checkbox>
            <el-checkbox v-model="jobForm.remote_allowed">允许远程工作</el-checkbox>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              {{ isEdit ? '更新岗位' : '发布岗位' }}
            </el-button>
            <el-button @click="handleSaveDraft" :loading="submitting" v-if="!isEdit">
              保存草稿
            </el-button>
            <el-button @click="handleBack">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { jobApi, companyApi } from '@/api/jobs'
import type { Job, Company } from '@/types'

const route = useRoute()
const router = useRouter()

// 响应式数据
const submitting = ref(false)
const jobFormRef = ref()
const companyList = ref<Company[]>([])
const salaryType = ref('range')
const validityType = ref('long_term')

// 判断是否为编辑模式
const isEdit = computed(() => route.name === 'JobEdit')
const jobId = computed(() => route.params.id ? Number(route.params.id) : null)

// 表单数据
const jobForm = reactive({
  company: '',
  title: '',
  job_type: 'full_time',
  work_mode: 'offline',
  department: '',
  salary_min: null as number | null,
  salary_max: null as number | null,
  salary_negotiable: false,
  work_location: '',
  remote_allowed: false,
  description: '',
  requirements: '',
  responsibilities: '',
  benefits: '',
  required_skills: '',
  preferred_skills: '',
  education_requirement: '',
  experience_requirement: '',
  positions_available: 1,
  application_deadline: '',
  contact_email: '',
  contact_phone: '',
  is_long_term: true,
  valid_from: '',
  valid_until: '',
  is_featured: false
})

// 表单验证规则
const jobRules = {
  company: [
    { required: true, message: '请选择所属公司', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入职位名称', trigger: 'blur' }
  ],
  job_type: [
    { required: true, message: '请选择工作性质', trigger: 'change' }
  ],
  work_mode: [
    { required: true, message: '请选择工作方式', trigger: 'change' }
  ],
  work_location: [
    { required: true, message: '请输入工作地区', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入职位描述', trigger: 'blur' }
  ],
  responsibilities: [
    { required: true, message: '请输入岗位职责', trigger: 'blur' }
  ],
  requirements: [
    { required: true, message: '请输入任职要求', trigger: 'blur' }
  ],
  positions_available: [
    { required: true, message: '请输入招聘人数', trigger: 'blur' }
  ],
  contact_email: [
    { required: true, message: '请输入投递邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  salary_min: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (salaryType.value === 'range' && !value) {
          callback(new Error('请输入最低薪资'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  salary_max: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (salaryType.value === 'range' && !value) {
          callback(new Error('请输入最高薪资'))
        } else if (salaryType.value === 'range' && jobForm.salary_min && value < jobForm.salary_min) {
          callback(new Error('最高薪资不能低于最低薪资'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  valid_from: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (validityType.value === 'date_range' && !value) {
          callback(new Error('请选择有效期开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  valid_until: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (validityType.value === 'date_range' && !value) {
          callback(new Error('请选择有效期结束时间'))
        } else if (validityType.value === 'date_range' && jobForm.valid_from && value <= jobForm.valid_from) {
          callback(new Error('有效期结束时间必须晚于开始时间'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 监听薪资类型变化
watch(salaryType, (newType) => {
  if (newType === 'negotiable') {
    jobForm.salary_negotiable = true
    jobForm.salary_min = null
    jobForm.salary_max = null
  } else {
    jobForm.salary_negotiable = false
  }
})

// 监听有效期类型变化
watch(validityType, (newType) => {
  if (newType === 'long_term') {
    jobForm.is_long_term = true
    jobForm.valid_from = ''
    jobForm.valid_until = ''
  } else {
    jobForm.is_long_term = false
  }
})

// 方法
const loadCompanies = async () => {
  try {
    const response = await companyApi.getCompanyList()
    companyList.value = response.data.results || []
  } catch (error) {
    console.error('获取公司列表失败:', error)
    ElMessage.error('获取公司列表失败')
  }
}

const loadJobDetail = async () => {
  if (!jobId.value) return

  try {
    const response = await jobApi.getJobDetail(jobId.value)
    const job = response.data

    // 填充表单数据
    Object.keys(jobForm).forEach(key => {
      if (job[key] !== undefined) {
        (jobForm as any)[key] = job[key]
      }
    })

    // 设置薪资类型
    salaryType.value = job.salary_negotiable ? 'negotiable' : 'range'

    // 设置有效期类型
    validityType.value = job.is_long_term ? 'long_term' : 'date_range'

  } catch (error) {
    console.error('获取岗位详情失败:', error)
    ElMessage.error('获取岗位详情失败')
    handleBack()
  }
}

const handleSubmit = async () => {
  if (!jobFormRef.value) return

  try {
    await jobFormRef.value.validate()

    submitting.value = true

    const formData = { ...jobForm }

    if (isEdit.value && jobId.value) {
      await jobApi.updateJob(jobId.value, formData)
      ElMessage.success('岗位更新成功')
    } else {
      formData.status = 'published'
      await jobApi.createJob(formData)
      ElMessage.success('岗位发布成功')
    }

    handleBack()

  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitting.value = false
  }
}

const handleSaveDraft = async () => {
  if (!jobFormRef.value) return

  try {
    await jobFormRef.value.validate()

    submitting.value = true

    const formData = { ...jobForm }
    formData.status = 'draft'

    await jobApi.createJob(formData)
    ElMessage.success('草稿保存成功')
    handleBack()

  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存草稿失败')
  } finally {
    submitting.value = false
  }
}

const handleBack = () => {
  router.push('/jobs/list')
}

// 生命周期
onMounted(() => {
  loadCompanies()
  if (isEdit.value) {
    loadJobDetail()
  }
})
</script>

<style lang="scss" scoped>
.job-form {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .form-content {
    padding: 20px;
    max-width: 1000px;
    margin: 0 auto;
  }

  .el-divider {
    margin: 30px 0 20px 0;

    .el-divider__text {
      font-weight: 600;
      color: #303133;
    }
  }

  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>